<template>
  <div>
    <el-card class="box-card">
      <!-- 卡片顶部添加品牌按钮 -->
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        v-has="`btn.Trademark.add`"
        @click="addTrademark"
        >添加品牌</el-button
      >
      <el-table style="margin: 10px 0px" :data="TrademarkList" border>
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <!-- table-column:默认展示数据用div -->
        <el-table-column label="品牌名称" prop="tmName"> </el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row, $index }">
            <img :src="row.logoUrl" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateTrademark(row)"
            ></el-button>
            <el-popconfirm
              :title="`您确定要删除${row.tmName}?`"
              width="250px"
              icon="Delete"
              @confirm="deleteTrademark(row)"
            >
              <template #reference>
                <el-button
                  type="primary"
                  size="small"
                  icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :pager-count="9"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="getHasTrademark"
        @size-change="changeLimitPage"
      />
    </el-card>

    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
    >
      <el-form
        style="width: 80%"
        ref="formRef"
        :model="trademarkParams"
        :rules="rules"
      >
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input
            placeholder="请您输入品牌名称"
            v-model="trademarkParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <!-- upload组件属性:action图片上传路径书写/api,代理服务器不发送这次post请求  -->
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 具名插槽:footer -->
      <template #footer>
        <el-button type="primary" size="default" @click="cancel"
          >取消</el-button
        >
        <el-button type="primary" size="default" @click="confirm"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from "vue";
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from "@/api/product/trademark/index";
import type {
  TradeMarkResponseData,
  Records,
  TradeMark,
} from "@/api/product/trademark/type";
import type { UploadProps } from "element-plus";
import { ElMessage } from "element-plus";
const formRef = ref<any>();
// 校验品牌名称
const validateTmName = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请您输入品牌名称"));
  } else {
    if (trademarkParams.tmName !== "") {
      if (!formRef.value) return;
      formRef.value.validateField("tmName", () => null);
    }
    callback();
  }
};
// 校验品牌图片
const validateLogoUrl = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请选择要上传的品牌图片"));
  } else {
    if (trademarkParams.logoUrl !== "") {
      if (!formRef.value) return;
      formRef.value.validateField("logoUrl", () => null);
    }
    callback();
  }
};
const rules = reactive({
  tmName: [{ validator: validateTmName, trigger: "blur", required: true }],
  logoUrl: [{ validator: validateLogoUrl, trigger: "change" }],
});
let dialogFormVisible = ref<boolean>(false);
//  当前页码
let pageNo = ref<number>(1);
//每一页展示多少条数据
let limit = ref<number>(3);
//品牌列表
let TrademarkList = ref<Records>([]);
//存储已有品牌数据总数
let total = ref<number>(0);
//定义收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: "",
  logoUrl: "",
});
onMounted(() => {
  getHasTrademark();
});
// 添加品牌
const addTrademark = () => {
  dialogFormVisible.value = true;
  trademarkParams.tmName = "";
  trademarkParams.logoUrl = "";
  trademarkParams.id = 0;
  nextTick(() => {
    formRef.value.clearValidate("logoUrl");
    formRef.value.clearValidate("tmName");
  });
};
const getHasTrademark = async (page = 1) => {
  pageNo.value = page;
  let result: TradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    limit.value
  );
  if (result.code == 200) {
    TrademarkList.value = result.data.records;
    total.value = result.data.total;
  }
};
const changeLimitPage = () => {
  getHasTrademark();
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile: any) => {
  if (rawFile.type !== "image/png") {
    ElMessage.error("图片必须是png格式");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过2MB!");
    return false;
  }
  return true;
};
// 图片上传成功
const handleAvatarSuccess: UploadProps["onSuccess"] = (response: any) => {
  trademarkParams.logoUrl = response.data;
  //图片上传成功,清除掉对应图片校验结果
  formRef.value.clearValidate("logoUrl");
};
// 取消
const cancel = () => {
  dialogFormVisible.value = false;
};
// 点击编辑按钮
const updateTrademark = (row: TradeMark) => {
  nextTick(() => {
    formRef.value.clearValidate("logoUrl");
    formRef.value.clearValidate("tmName");
  });
  trademarkParams.tmName = row.tmName;
  trademarkParams.logoUrl = row.logoUrl;
  trademarkParams.id = row.id;
  dialogFormVisible.value = true;
};
// 确定
const confirm = async () => {
  await formRef.value.validate();
  let result = await reqAddOrUpdateTrademark(trademarkParams);
  if (result.code == 200) {
    dialogFormVisible.value = false;
    ElMessage({
      message: trademarkParams.id ? "修改成功" : "新增成功",
      type: "success",
    });
    getHasTrademark(trademarkParams.id ? pageNo.value : 1);
  } else {
    //添加品牌失败
    ElMessage({
      type: "error",
      message: trademarkParams.id ? "修改品牌失败" : "添加品牌失败",
    });
    //关闭对话框
    dialogFormVisible.value = false;
  }
};
// 删除品牌
const deleteTrademark = async (row: TradeMark) => {
  let result = await reqDeleteTrademark(row.id as number);
  if (result.code == 200) {
    //删除成功提示信息
    ElMessage({
      type: "success",
      message: "删除品牌成功",
    });
    getHasTrademark(TrademarkList.value.length > 1 ? pageNo.value : pageNo.value - 1);
  }else{
    ElMessage({
      type: "error",
      message: "删除品牌失败",
    });
  }
};
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
